<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>会话隔离测试</title>
    <style>
        body {
            font-family: Arial, sans-serif;
            max-width: 800px;
            margin: 20px auto;
            padding: 20px;
            background: #f0f2f5;
        }
        .container {
            background: white;
            padding: 30px;
            border-radius: 10px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 20px;
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 30px;
        }
        .form-group {
            margin-bottom: 20px;
        }
        label {
            display: block;
            margin-bottom: 5px;
            font-weight: bold;
            color: #555;
        }
        input {
            width: 100%;
            padding: 12px;
            border: 1px solid #ddd;
            border-radius: 5px;
            box-sizing: border-box;
            font-size: 16px;
        }
        .button-group {
            display: flex;
            gap: 10px;
            margin: 20px 0;
            flex-wrap: wrap;
        }
        button {
            padding: 12px 16px;
            border: none;
            border-radius: 5px;
            font-size: 14px;
            cursor: pointer;
            transition: background-color 0.3s;
            min-width: 120px;
        }
        .primary { background: #007bff; color: white; }
        .primary:hover { background: #0056b3; }
        .secondary { background: #6c757d; color: white; }
        .secondary:hover { background: #545b62; }
        .success { background: #28a745; color: white; }
        .success:hover { background: #1e7e34; }
        .warning { background: #ffc107; color: #212529; }
        .warning:hover { background: #e0a800; }
        .info {
            background: #e3f2fd;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            border-left: 4px solid #2196f3;
        }
        .warning-box {
            background: #fff3cd;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            border-left: 4px solid #ffc107;
        }
        .success-box {
            background: #d4edda;
            padding: 20px;
            border-radius: 8px;
            margin: 20px 0;
            border-left: 4px solid #28a745;
        }
        .status {
            background: #f8f9fa;
            padding: 15px;
            border-radius: 5px;
            font-family: monospace;
            font-size: 12px;
            white-space: pre-wrap;
            margin: 20px 0;
            border: 1px solid #dee2e6;
            max-height: 300px;
            overflow-y: auto;
        }
        .session-info {
            position: fixed;
            top: 20px;
            right: 20px;
            background: #343a40;
            color: white;
            padding: 10px 15px;
            border-radius: 5px;
            font-size: 12px;
            z-index: 1000;
            max-width: 200px;
        }
        .current-user {
            background: #e8f5e8;
            padding: 15px;
            border-radius: 8px;
            margin: 20px 0;
            border: 2px solid #28a745;
        }
        .quick-users {
            display: flex;
            gap: 10px;
            margin: 15px 0;
            flex-wrap: wrap;
        }
        .user-btn {
            background: #f8f9fa;
            border: 1px solid #dee2e6;
            padding: 8px 12px;
            border-radius: 5px;
            cursor: pointer;
            font-size: 12px;
            transition: all 0.3s;
        }
        .user-btn:hover {
            background: #e9ecef;
            border-color: #adb5bd;
        }
        .step {
            background: #f8f9fa;
            padding: 15px;
            margin: 10px 0;
            border-radius: 5px;
            border-left: 4px solid #007bff;
        }
        .step-number {
            background: #007bff;
            color: white;
            width: 24px;
            height: 24px;
            border-radius: 50%;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: bold;
            margin-right: 10px;
        }
    </style>
</head>
<body>
    <div class="session-info" id="sessionInfo">检测会话中...</div>
    
    <div class="container">
        <h1>🔒 SessionBox 会话隔离测试</h1>
        
        <div class="warning-box">
            <strong>⚠️ 重要说明：</strong><br>
            localStorage/sessionStorage 每次保存都会<strong>覆盖</strong>之前的数据，这是正常行为！<br>
            会话隔离的测试重点是：<strong>不同标签页之间的数据是否独立</strong>。
        </div>
        
        <div class="info">
            <strong>📋 正确的测试步骤：</strong>
            <div class="step">
                <span class="step-number">1</span>
                在此页面保存用户A的登录信息
            </div>
            <div class="step">
                <span class="step-number">2</span>
                打开SessionBox扩展，点击"在此页面创建会话"
            </div>
            <div class="step">
                <span class="step-number">3</span>
                在新标签页中点击"加载登录信息"
            </div>
            <div class="step">
                <span class="step-number">4</span>
                如果新页面显示"没有找到登录信息"，说明隔离成功！
            </div>
            <div class="step">
                <span class="step-number">5</span>
                在新页面保存用户B的信息，两个页面应该互不影响
            </div>
        </div>
    </div>

    <div class="container">
        <h3>👤 当前登录用户</h3>
        <div class="current-user" id="currentUser">
            <strong>当前用户：</strong><span id="currentUserDisplay">无</span><br>
            <strong>登录时间：</strong><span id="loginTimeDisplay">无</span>
        </div>
        
        <h3>🚀 快速测试用户</h3>
        <div class="quick-users">
            <button class="user-btn" onclick="quickLogin('张三', 'password123')">👨 张三</button>
            <button class="user-btn" onclick="quickLogin('李四', 'password456')">👩 李四</button>
            <button class="user-btn" onclick="quickLogin('王五', 'password789')">👨 王五</button>
            <button class="user-btn" onclick="quickLogin('赵六', 'passwordabc')">👩 赵六</button>
        </div>
        
        <div class="form-group">
            <label for="username">用户名：</label>
            <input type="text" id="username" placeholder="请输入用户名">
        </div>
        
        <div class="form-group">
            <label for="password">密码：</label>
            <input type="password" id="password" placeholder="请输入密码">
        </div>
        
        <div class="button-group">
            <button class="primary" onclick="saveLogin()">💾 保存登录信息</button>
            <button class="secondary" onclick="loadLogin()">📂 加载登录信息</button>
            <button class="success" onclick="clearLogin()">🗑️ 清除登录信息</button>
        </div>
        
        <div class="button-group">
            <button class="warning" onclick="setCookies()">🍪 设置测试Cookie</button>
            <button class="secondary" onclick="showStatus()">📊 显示详细状态</button>
            <button class="primary" onclick="testIsolation()">🧪 测试隔离状态</button>
        </div>
    </div>

    <div class="container">
        <h3>📊 存储状态</h3>
        <div id="status" class="status">点击"显示详细状态"查看当前存储状态</div>
    </div>

    <script>
        // 快速登录
        function quickLogin(username, password) {
            document.getElementById('username').value = username;
            document.getElementById('password').value = password;
            saveLogin();
        }

        // 保存登录信息
        function saveLogin() {
            const username = document.getElementById('username').value;
            const password = document.getElementById('password').value;
            
            if (!username || !password) {
                alert('请输入用户名和密码');
                return;
            }
            
            const loginTime = new Date().toISOString();
            
            // 保存到localStorage
            localStorage.setItem('currentUser', username);
            localStorage.setItem('userPassword', password);
            localStorage.setItem('loginTime', loginTime);
            localStorage.setItem('sessionData', JSON.stringify({
                user: username,
                loginTime: loginTime,
                sessionId: 'sess_' + Date.now()
            }));
            
            // 保存到sessionStorage
            sessionStorage.setItem('activeUser', username);
            sessionStorage.setItem('sessionId', 'sess_' + Date.now());
            sessionStorage.setItem('isLoggedIn', 'true');
            
            // 设置Cookie
            document.cookie = `currentUser=${username}; path=/`;
            document.cookie = `loginStatus=true; path=/`;
            document.cookie = `sessionTime=${Date.now()}; path=/`;
            
            updateCurrentUserDisplay();
            alert(`✅ ${username} 的登录信息已保存`);
            showStatus();
        }
        
        // 加载登录信息
        function loadLogin() {
            const username = localStorage.getItem('currentUser') || '';
            const password = localStorage.getItem('userPassword') || '';
            
            document.getElementById('username').value = username;
            document.getElementById('password').value = password;
            
            updateCurrentUserDisplay();
            
            if (username && password) {
                alert(`✅ ${username} 的登录信息已加载`);
            } else {
                alert('❌ 没有找到保存的登录信息');
            }
            showStatus();
        }
        
        // 更新当前用户显示
        function updateCurrentUserDisplay() {
            const username = localStorage.getItem('currentUser') || '无';
            const loginTime = localStorage.getItem('loginTime') || '无';
            
            document.getElementById('currentUserDisplay').textContent = username;
            document.getElementById('loginTimeDisplay').textContent = 
                loginTime !== '无' ? new Date(loginTime).toLocaleString() : '无';
        }
        
        // 清除登录信息
        function clearLogin() {
            localStorage.clear();
            sessionStorage.clear();
            
            // 清除Cookie
            document.cookie.split(";").forEach(function(c) { 
                document.cookie = c.replace(/^ +/, "").replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/"); 
            });
            
            document.getElementById('username').value = '';
            document.getElementById('password').value = '';
            
            updateCurrentUserDisplay();
            alert('✅ 所有登录信息已清除');
            showStatus();
        }
        
        // 设置测试Cookie
        function setCookies() {
            const timestamp = Date.now();
            const username = localStorage.getItem('currentUser') || 'testUser';
            
            document.cookie = `testCookie1=value1_${timestamp}; path=/`;
            document.cookie = `testCookie2=value2_${timestamp}; path=/`;
            document.cookie = `userToken=${username}_token_${timestamp}; path=/`;
            
            alert('✅ 测试Cookie已设置');
            showStatus();
        }
        
        // 测试隔离状态
        function testIsolation() {
            const isolationStatus = {
                '🔍 隔离测试结果': '---',
                '👤 当前用户': localStorage.getItem('currentUser') || '无',
                '🕒 登录时间': localStorage.getItem('loginTime') || '无',
                '📦 localStorage项目数': localStorage.length,
                '🗂️ sessionStorage项目数': sessionStorage.length,
                '🍪 Cookie数量': document.cookie.split(';').filter(c => c.trim()).length,
                '🌐 页面URL': window.location.href,
                '⏰ 检测时间': new Date().toLocaleString()
            };
            
            // 检测是否有数据
            if (localStorage.length > 0 || sessionStorage.length > 0 || document.cookie.trim()) {
                isolationStatus['🔍 隔离测试结果'] = '❌ 检测到数据存在 - 如果这是新会话页面，说明隔离失败';
            } else {
                isolationStatus['🔍 隔离测试结果'] = '✅ 没有检测到数据 - 如果这是新会话页面，说明隔离成功';
            }
            
            alert(JSON.stringify(isolationStatus, null, 2));
            showStatus();
        }
        
        // 显示详细状态
        function showStatus() {
            const status = {
                '🕒 检测时间': new Date().toLocaleString(),
                '🌐 页面URL': window.location.href,
                '👤 当前登录用户': localStorage.getItem('currentUser') || '无',
                '📦 localStorage详细内容': {},
                '🗂️ sessionStorage详细内容': {},
                '🍪 Cookie详细内容': document.cookie || '(无)',
                '🔧 API状态': {
                    'localStorage类型': typeof localStorage,
                    'sessionStorage类型': typeof sessionStorage,
                    'localStorage构造函数': localStorage.constructor.name,
                    'sessionStorage构造函数': sessionStorage.constructor.name,
                    'localStorage长度': localStorage.length,
                    'sessionStorage长度': sessionStorage.length
                }
            };
            
            // 收集localStorage
            try {
                for (let i = 0; i < localStorage.length; i++) {
                    const key = localStorage.key(i);
                    status['📦 localStorage详细内容'][key] = localStorage.getItem(key);
                }
            } catch (error) {
                status['📦 localStorage详细内容'] = '错误: ' + error.message;
            }
            
            // 收集sessionStorage
            try {
                for (let i = 0; i < sessionStorage.length; i++) {
                    const key = sessionStorage.key(i);
                    status['🗂️ sessionStorage详细内容'][key] = sessionStorage.getItem(key);
                }
            } catch (error) {
                status['🗂️ sessionStorage详细内容'] = '错误: ' + error.message;
            }
            
            document.getElementById('status').textContent = JSON.stringify(status, null, 2);
        }
        
        // 更新会话信息
        function updateSessionInfo() {
            const sessionInfo = document.getElementById('sessionInfo');
            
            if (window.chrome && chrome.runtime) {
                try {
                    chrome.runtime.sendMessage({action: 'getCurrentSession'}, (response) => {
                        if (response && response.session) {
                            sessionInfo.innerHTML = `
                                <strong>会话:</strong> ${response.session.name}<br>
                                <strong>ID:</strong> ${response.session.id.substring(0, 8)}...
                            `;
                            sessionInfo.style.background = response.session.color;
                        } else {
                            sessionInfo.textContent = '默认会话 (无隔离)';
                            sessionInfo.style.background = '#6c757d';
                        }
                    });
                } catch (error) {
                    sessionInfo.textContent = '扩展未连接';
                    sessionInfo.style.background = '#dc3545';
                }
            } else {
                sessionInfo.textContent = '非扩展环境';
                sessionInfo.style.background = '#6c757d';
            }
        }
        
        // 页面加载时初始化
        window.addEventListener('load', () => {
            console.log('SessionBox测试页面已加载');
            console.log('localStorage:', typeof localStorage, localStorage.constructor.name);
            console.log('sessionStorage:', typeof sessionStorage, sessionStorage.constructor.name);
            
            updateCurrentUserDisplay();
            loadLogin();
            showStatus();
            updateSessionInfo();
            
            // 定期更新会话信息
            setInterval(updateSessionInfo, 3000);
        });
        
        // 监听存储变化
        window.addEventListener('storage', (e) => {
            console.log('Storage事件:', e);
            updateCurrentUserDisplay();
            showStatus();
        });
    </script>
</body>
</html> 